//
//  AppConfig.m
//  SleepingElf
//
//  Created by karong on 2023/10/8.
//

#import "AppConfig.h"
#import <AudioToolbox/AudioToolbox.h>

// 震动添加结束的回调
void soundCompleteCallback( SystemSoundID  ssID, void* __nullable clientData);
void soundCompleteCallback( SystemSoundID  ssID, void* __nullable clientData) {
  // 震动效果
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
@interface AppConfig ()
///初始化AppConfig的时候会初始化以下属性 所以需要过滤

/// 音乐计时器 倒计时长，修改可更新倒计时 单位：秒
@property (nonatomic, assign) NSTimeInterval keepMusicTime;
@property (nonatomic, assign) NSTimeInterval currentMusicTime;
@property (nonatomic, strong) NSTimer * musicTimer;

/// 唤醒计时器 倒计时长，修改可更新倒计时 单位：秒
@property (nonatomic, assign) NSTimeInterval keepWakeUpTime;
@property (nonatomic, assign) NSTimeInterval currentWakeUpTime;
@property (nonatomic, strong) NSTimer * wakeUpTimer;
@end

@implementation AppConfig
static AppConfig *instanceAppConfig = nil;

+ (NSArray *)mj_ignoredPropertyNames {
    return @[@"time_difference", @"wakeUpType", @"playList", @"sleepConfig", @"xiaoQiConfig", @"musicTimer", @"wakeUpTimer", @"keepMusicTime", @"currentMusicTime", @"keepWakeUpTime", @"currentWakeUpTime"];
}

+ (NSDictionary *)mj_objectClassInArray {
    return @{@"lastMusicArray":NSClassFromString(@"MusicModel"),
             @"playHistory":NSClassFromString(@"MusicModel")};
}

+ (instancetype)defaultSession {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instanceAppConfig = [[self alloc] init];
    });
    return instanceAppConfig;
}

- (instancetype)init {
    if([appUserDefaults objectForKey:@"AppConfig"]) {
        self = [[AppConfig alloc] mj_setKeyValues:[appUserDefaults objectForKey:@"AppConfig"]];
    }
    else {
        self = [super init];
        self.languageType = 0;
    }
    self.sleepConfig = [SleepConfig new];
    self.sleepConfig.title = WSLocalized(@"下雨天");
    self.sleepConfig.url = @"rain";
    self.xiaoQiConfig = [XiaoQiConfig new];
    self.xiaoQiConfig.title = WSLocalized(@"下雨天");
    self.xiaoQiConfig.url = @"rain";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationWillTerminateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationDidEnterBackgroundNotification object:nil];
    return self;
}

- (void)save {
    @try {
        [appUserDefaults setObject:instanceAppConfig.mj_keyValues forKey:@"AppConfig"];
    } @catch (NSException *exception) {
        [appUserDefaults removeObjectForKey:@"AppConfig"];
    } @finally {
        [appUserDefaults synchronize];
    }
}

- (NSString *)aes_key {
    if (!_aes_key) {
        NSString * host = API_HOST;
        NSString * md5 = [host.lowercaseString md5String];
        _aes_key = [md5 substringWithRange:NSMakeRange(8, 16)];
    }
    return _aes_key;
}

- (NSString *)aes_iv {
    if (!_aes_iv) {
        unsigned long len;
        len = [self.aes_key length];
        unichar a[len];
        for(int i = 0; i < len; i++) {
            unichar c = [self.aes_key characterAtIndex:len-i-1];
            a[i] = c;
        }
        _aes_iv = [NSString stringWithCharacters:a length:len];
    }
    return _aes_iv;
}

- (void)addHistoryMusic:(MusicModel *)music {
    if (music.id <= 0) {
        return;
    }
    BOOL rec = NO;
    for (int i = 0; i < self.playHistory.count; i ++) {
        MusicModel * object = self.playHistory[i];
        if (object.id == music.id) {
            [self.playHistory removeObject:object];
            [self.playHistory insertObject:music atIndex:0];
            rec = YES;
            break;
        }
    }
    if (!rec) {
        [self.playHistory insertObject:music atIndex:0];
    }
}

- (NSMutableArray *)playHistory {
    if (!_playHistory) {
        _playHistory = [NSMutableArray new];
    }
    return _playHistory;
}

- (NSTimer *)musicTimer {
    if (!_musicTimer) {
        _musicTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(musicTimeKeeper) userInfo:nil repeats:YES];
    }
    return _musicTimer;
}

- (void)musicTimeKeeper {
    self.currentMusicTime --;
    if(self.currentMusicTime > 0) {// 更新倒计时
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%f", self.currentMusicTime);
        });
    }
    else {
        // 倒计时结束，关闭
        [self stopMusicTimeKeeper];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[PlayerManager shared]pause];
            appConfig.sleepConfig.autoClose = NO;
            appConfig.sleepConfig.autoCloseTimeType = 0;
            [[NSNotificationCenter defaultCenter] postNotificationName:SESleepSettingNotification object:nil];
        });
    }
}

- (void)starMusicTimeKeeper:(NSTimeInterval)keepTime {
    self.keepMusicTime = keepTime;
    self.currentMusicTime = keepTime;
    [self.musicTimer fire];
    [[PlayerManager shared] keepAlive];
}

- (void)stopMusicTimeKeeper {
    [self.musicTimer invalidate];
    self.musicTimer = nil;
}

- (NSTimer *)wakeUpTimer {
    if (!_wakeUpTimer) {
        _wakeUpTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(wakeUpTimeKeeper) userInfo:nil repeats:YES];
    }
    return _wakeUpTimer;
}

- (void)wakeUpTimeKeeper {
    self.currentWakeUpTime --;
    if(self.currentWakeUpTime > 0) {// 更新倒计时
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:SEKeepTimeChangeNotification object:@(self.currentWakeUpTime)];
        });
        NSLog(@"%f", self.currentWakeUpTime);
    }
    else {
        [self stopWakeUpTimeKeeper];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[PlayerManager shared]pause];
            if (appConfig.wakeUpType == 1) {
                [[PlayerManager shared]wakeUpWithMusicUrl:self.xiaoQiConfig.url];
                [[NSNotificationCenter defaultCenter] postNotificationName:SEKeepTimeChangeNotification object:@(self.currentWakeUpTime)];
            }
            if (appConfig.wakeUpType == 2) {
                if (appConfig.sleepConfig.shake) {
                    // 开始震动并添加震动都回调
                    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, soundCompleteCallback, NULL);
                }
                [[PlayerManager shared]wakeUpWithMusicUrl:self.sleepConfig.url];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self defaultTimeKeeper];
                    if (self.sleepConfig.playAgainTime > 0 && self.sleepConfig.playAgainMint > 0) {
                        self.sleepConfig.playAgainTime --;
                        self.sleepConfig.time = 10;//self.sleepConfig.playAgainMint;
                        [self.sleepConfig starTimeKeeper];
                    }
                    else {
                        [[NSNotificationCenter defaultCenter] postNotificationName:SEKeepTimeChangeNotification object:@(self.currentWakeUpTime)];
                    }
                });
            }
        });
    }
}

- (void)starWakeUpTimeKeeper:(NSTimeInterval)keepTime {
    self.keepWakeUpTime = keepTime;
    self.currentWakeUpTime = keepTime;
    [self.wakeUpTimer fire];
}

- (void)stopWakeUpTimeKeeper {
    [self.wakeUpTimer invalidate];
    self.wakeUpTimer = nil;
}

- (void)defaultTimeKeeper {
    [self stopWakeUpTimeKeeper];
    [[PlayerManager shared] stopWakeUp];
    AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
    AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
}
@end

@implementation SleepConfig
- (void)setAutoClose:(BOOL)autoClose {
    _autoClose = autoClose;
    if (autoClose) {
        [appConfig starMusicTimeKeeper:self.autoCloseTime*60];
    }
    else {
        [appConfig stopMusicTimeKeeper];
    }
}

- (void)starTimeKeeper {
    [appConfig starWakeUpTimeKeeper:self.time];
    [[PlayerManager shared] keepAlive];
}

- (void)setAutoCloseTime:(NSInteger)autoCloseTime {
    _autoCloseTime = autoCloseTime;
    if (self.autoClose) {
        [appConfig starMusicTimeKeeper:autoCloseTime];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:SESleepSettingNotification object:nil];
}

- (void)setPlayAgainTime:(NSInteger)playAgainTime {
    _playAgainTime = playAgainTime;
    [[NSNotificationCenter defaultCenter] postNotificationName:SESleepSettingNotification object:nil];
}

- (void)setTitle:(NSString *)title {
    _title = title;
    [[NSNotificationCenter defaultCenter] postNotificationName:SESleepSettingNotification object:nil];
}
@end

@implementation XiaoQiConfig
- (void)setTitle:(NSString *)title {
    _title = title;
    [[NSNotificationCenter defaultCenter] postNotificationName:SESleepSettingNotification object:nil];
}

- (void)starTimeKeeper {
    [appConfig starWakeUpTimeKeeper:self.time];
    [[PlayerManager shared] keepAlive];
}
@end
